﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;

namespace Freshome.p.fox
{
    public class ExceptaskAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.Controller.ViewData["ErrorMessage"] = filterContext.Exception.Message;
                using (var logger = new EventLog("Kingate"))
                {
                    logger.Source = "Freshome";
                    if (EventLog.Exists(logger.Log) && EventLog.SourceExists(logger.Source))
                    {
                        var ex = filterContext.Exception;
                        while (ex.InnerException != null)
                        {
                            ex = ex.InnerException;
                        }
                        logger.WriteEntry(string.Format("Controller:\t{0}\nAction:\t{1}\nException:\t{2}",
                            filterContext.RouteData.Values["Controller"], filterContext.RouteData.Values["Action"], ex.Message),
                            EventLogEntryType.Error);
                    }
                }
                filterContext.Result = new ViewResult()
                {
                    ViewName = "Error",
                    ViewData = filterContext.Controller.ViewData
                };
                filterContext.ExceptionHandled = true;
            }
        }
    }
}